<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/3/20
 * Time: 11:46
 */

namespace app\queue\articlepart;

use app\common\lib\Ai\OpenApi;
use app\common\lib\Common;
use app\common\lib\Guzzle;
use app\common\lib\Puppeteer;
use app\common\lib\RedisQueue;
use app\common\lib\TencentAsr;
use app\common\lib\TencentIvld;
use app\exception\IndexException;
use app\model\redis\RedisQueueModel;
use app\model\user\UserPromotionArticleModel;
use app\model\user\UserPromotionVideoModel;
use app\model\video\AsyncUploadVideoIvldModel;
use support\Cache;
use Webman\RedisQueue\Consumer;
use app\common\lib\TencentCos;

class AsyncArticlePart  implements Consumer
{
    // 要消费的队列名
    public $queue = 'asyncArticlePart';

    // 连接名，对应 plugin/webman/redis-queue/redis.php 里的连接`
    public $connection = 'default';

    protected $resultData = [];

    // 消费
    public function consume($data)
    {
        Common::initQueueConfig();

        $queue = RedisQueueModel::getInstance()->find($data['queueid']);
        $queue->exec_time = date('Y-m-d H:i:s');
        $queue->save();

        try{

            $result = $this->handle($data);

            RedisQueue::getInstance()->saveQueue($this->queue,$data,$result);
        }catch (\Throwable $e){
            RedisQueue::getInstance()->saveQueue($this->queue,$data,['error'=>$e->getMessage()]);
            Common::queueExecptionReport($queue,$data,$e);
        }
    }

    protected function handle($data)
    {
        $requestId = $data['requestid'];
        $article = UserPromotionArticleModel::getInstance()->find($data['id']);
        if(empty($article['content'])){
            throw new IndexException(4020,'文章内容为空');
        }
        $parts = [];

        try{
            //用户ai分段
            $parts = Common::aiContentPartsToUser($article['content']);

        }catch (IndexException $e){
            if($e->getCode()==4049 || strpos($e->getMessage(),'敏感词')!==false){
                $article->status = 3;
                $article->message = $e->getMessage();
                $article->save();
                throw new IndexException(4020,$e->getMessage());
            }
        }

        if(empty($parts)){
            $article->status = 2;
            $article->message = 'AI分析失败,请稍后再试';
            $article->save();

            throw new IndexException(4020,'AI分析失败,请稍后再试');
        }

        //分段分析和字幕
        list($parts,$subTitles) = partsAnalyze($parts);

        $article->part_content = json_encode(array_values($parts),256);
        $article->subtitle = json_encode($subTitles,256);
        $article->status = 1;
        $article->message = 'AI分析成功';
        $article->save();

        return ['AI分析成功'];
    }

    // 消费失败回调
    /*
    $package = [
        'id' => 1357277951, // 消息ID
        'time' => 1709170510, // 消息时间
        'delay' => 0, // 延迟时间
        'attempts' => 2, // 消费次数
        'queue' => 'send-mail', // 队列名
        'data' => ['to' => 'tom@gmail.com', 'content' => 'hello'], // 消息内容
        'max_attempts' => 5, // 最大重试次数
        'error' => '错误信息' // 错误信息
    ]
    */
    public function onConsumeFailure(\Throwable $e, $package)
    {
//        echo "consume failure\n";
//        echo $e->getMessage() . "\n";
//        // 无需反序列化
//        var_export($package);

        RedisQueue::getInstance()->saveQueue($this->queue,$package['data'],['error'=>$e->getMessage()]);
    }

}